<template>
  <view class="page">
    <!-- 收益统计卡片 -->
    <view class="income-card">
      <view class="card-header">
        <text class="card-title">我的收益</text>
        <text class="card-subtitle">收益统计</text>
      </view>
      <view class="income-stats">
        <view class="stat-item">
          <text class="stat-value">￥{{ totalIncome.toFixed(2) }}</text>
          <text class="stat-label">累计收益</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">￥{{ availableIncome.toFixed(2) }}</text>
          <text class="stat-label">可用余额</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">￥{{ frozenIncome.toFixed(2) }}</text>
          <text class="stat-label">冻结金额</text>
        </view>
      </view>
    </view>

    <!-- 收益类型筛选 -->
    <view class="filter-tabs">
      <view 
        class="tab-item" 
        :class="activeTab === 'all' ? 'active' : ''"
        @click="changeTab('all')"
      >
        全部
      </view>
      <view 
        class="tab-item" 
        :class="activeTab === 1 ? 'active' : ''"
        @click="changeTab(1)"
      >
        见单奖
      </view>
      <view 
        class="tab-item" 
        :class="activeTab === 2 ? 'active' : ''"
        @click="changeTab(2)"
      >
        平级奖
      </view>
      <view 
        class="tab-item" 
        :class="activeTab === 3 ? 'active' : ''"
        @click="changeTab(3)"
      >
        直推奖
      </view>
      <view 
        class="tab-item" 
        :class="activeTab === 4 ? 'active' : ''"
        @click="changeTab(4)"
      >
        分红
      </view>
    </view>

    <!-- 收益记录列表 -->
    <view class="income-list">
      <view class="list-item" v-for="item in incomeList" :key="item.id">
        <view class="item-left">
          <view class="income-icon" :class="getIncomeTypeClass(item.income_type)">
            <text class="iconfont" :class="getIncomeIcon(item.income_type)"></text>
          </view>
          <view class="income-info">
            <view class="income-title">{{ getIncomeTypeText(item.income_type) }}</view>
            <view class="income-source">来源：{{ item.from_user?.nickname || '用户' + item.from_user_id }}</view>
            <view class="income-condition" v-if="item.unfreeze_condition">{{ item.unfreeze_condition }}</view>
            <view class="income-time">{{ formatTime(item.create_time) }}</view>
          </view>
        </view>
        <view class="item-right">
          <view class="income-amount" :class="item.status === 1 ? 'success' : 'pending'">
            +￥{{ parseFloat(item.amount).toFixed(2) }}
            <!-- 只有平级奖且没有特殊解冻标记且冻结金额大于0时才显示冻结信息 -->
            <text v-if="item.income_type === 2 && !hasSpecialUnfreeze && item.frozen_amount && parseFloat(item.frozen_amount) > 0" class="frozen-amount">
              (冻结: ￥{{ getLevelBonusFrozenAmount(item).toFixed(2) }})
            </text>
          </view>
          <view class="income-status">
            <!-- 解冻倒计时显示 - 只有平级奖显示 -->
            <view v-if="item.income_type === 2 && getLevelBonusFrozenAmount(item) > 0 && getUnfreezeTimeLeft(item) > 0" class="unfreeze-countdown">
              <tm-countdown 
                :time="getUnfreezeTimeLeft(item) * 1000" 
                :autoStart="true" 
                @end="onUnfreezeTimeEnd(item.id)"
                format="MM分SS秒"
                color="#E23737"
              ></tm-countdown>
              <text class="countdown-text">{{ getUnfreezeText(item) }}</text>
            </view>
            <!-- 状态文本 -->
            <text v-else class="status-text" :class="getStatusClass(item.status)">
              {{ getStatusTextForDisplay(item) }}
            </text>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore">
        <tm-button size="small" color="grey" @click="loadMore" :loading="loading">
          {{ loading ? '加载中...' : '加载更多' }}
        </tm-button>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="incomeList.length === 0 && !loading">
        <tm-result :showBtn="false" subTitle="暂时还没有收益记录哦~" title="暂无收益" color="#bc8c1e"></tm-result>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue'
import { onLoad, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
import { getLinkageIncomeLogs, getLinkageIncomeStats, checkSpecialUnfreeze } from '@/utils/api'

// 数据定义
const activeTab = ref<string | number>('all')
const incomeList = ref<any[]>([])
const loading = ref(false)
const hasMore = ref(true)
const page = ref(1)
const limit = 20

// 收益统计数据
const incomeStats = ref({
  total_income: 0,
  available_income: 0,
  frozen_income: 0,
  see_order_bonus: 0,
  level_bonus: 0,
  direct_bonus: 0,
  today_income: 0,
  month_income: 0,
  total_count: 0
})

// 特殊解冻标记
const hasSpecialUnfreeze = ref(false)

// 使用后端统计数据计算累计收益
const totalIncome = computed(() => {
  return incomeStats.value.total_income || 0
})

// 使用后端统计数据计算可用余额
const availableIncome = computed(() => {
  let available = parseFloat(incomeStats.value.frozen_amount || 0)
  
  // 如果有特殊解冻标记，将冻结金额加回可用余额
  if (hasSpecialUnfreeze.value) {
    const frozenAmount = totalIncome.value - available
    available += frozenAmount
  }
  
  return available
})

// 计算冻结金额：累计收益 - 可用余额
const frozenIncome = computed(() => {
  // 如果有特殊解冻标记，冻结金额为0（因为已经加回可用余额）
  if (hasSpecialUnfreeze.value) {
    return 0
  }
  
  return totalIncome.value - availableIncome.value
})

// 页面加载
onLoad(() => {
  loadSpecialUnfreezeStatus()
  loadIncomeStats()
  loadIncomeList()
})

onPullDownRefresh(() => {
  refreshData()
})

onReachBottom(() => {
  if (hasMore.value && !loading.value) {
    loadMore()
  }
})

// 监听标签切换
watch(activeTab, () => {
  refreshData()
})

// 切换标签
const changeTab = (tab: string | number) => {
  activeTab.value = tab
}

// 刷新数据
const refreshData = () => {
  page.value = 1
  hasMore.value = true
  incomeList.value = []
  loadSpecialUnfreezeStatus()
  loadIncomeStats()
  loadIncomeList().finally(() => {
    uni.stopPullDownRefresh()
  })
}

// 加载特殊解冻标记状态
const loadSpecialUnfreezeStatus = async () => {
  try {
    const res = await checkSpecialUnfreeze({})
    if (res.code === 1 && res.data) {
      hasSpecialUnfreeze.value = res.data.has_special_unfreeze
      console.log('特殊解冻标记状态:', res.data)
    }
  } catch (error) {
    console.error('加载特殊解冻标记失败:', error)
  }
}

// 加载收益统计
const loadIncomeStats = async () => {
  try {
    const res = await getLinkageIncomeStats({})
    if (res.code === 1 && res.data) {
      incomeStats.value = res.data
    }
  } catch (error) {
    console.error('加载收益统计失败:', error)
  }
}

// 加载收益列表
const loadIncomeList = async () => {
  if (loading.value) return
  loading.value = true
  
  try {
    const params: any = {
      page: page.value,
      limit
    }
    
    if (activeTab.value !== 'all') {
      params.income_type = activeTab.value
    }
    
    const res = await getLinkageIncomeLogs(params)
    
    // 调试信息
    console.log('API响应:', res)
    console.log('收益数据:', res.data?.data)
    
    if (res.code === 1 && res.data) {
      const newList = res.data.data || []
      console.log('解析后的列表:', newList)
      
      if (page.value === 1) {
        incomeList.value = newList
      } else {
        incomeList.value.push(...newList)
      }
      
      hasMore.value = newList.length >= limit
      console.log('最终收益列表:', incomeList.value)
    } else {
      console.error('API调用失败:', res)
      uni.showToast({
        title: res.msg || '加载失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('加载收益列表失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  page.value++
  loadIncomeList()
}

// 获取收益类型文本
const getIncomeTypeText = (type: number) => {
  switch (type) {
    case 1:
      return '见单奖'
    case 2:
      return '平级奖'
    case 3:
      return '直推奖'
    case 4:
      return '分红'
    default:
      return '其他收益'
  }
}

// 获取收益类型样式类
const getIncomeTypeClass = (type: number) => {
  switch (type) {
    case 1:
      return 'see-order'
    case 2:
      return 'level-bonus'
    case 3:
      return 'direct-bonus'
    case 4:
      return 'dividend'
    default:
      return 'other'
  }
}

// 获取收益图标
const getIncomeIcon = (type: number) => {
  switch (type) {
    case 1:
      return 'icon-gift'
    case 2:
      return 'icon-trophy'
    case 3:
      return 'icon-star'
    case 4:
      return 'icon-dividend'
    default:
      return 'icon-money'
  }
}

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 1:
      return '已到账'
    case 2:
      return '冻结中'
    case 3:
      return '已失效'
    default:
      return '处理中'
  }
}

// 获取状态文本（根据冻结金额判断）
const getStatusTextByFrozen = (item: any) => {
  if (item.frozen_amount && parseFloat(item.frozen_amount) > 0) {
    return '部分冻结'
  }
  return getStatusText(item.status)
}

// 获取平级奖的冻结金额（80%部分）
const getLevelBonusFrozenAmount = (item: any) => {
  if (item.income_type === 2) {
    // 如果有特殊解冻标记，不显示冻结金额
    if (hasSpecialUnfreeze.value) {
      return 0
    }
    const totalAmount = parseFloat(item.amount || 0)
    const level_bonus_special_rate = 0.80
    return totalAmount * level_bonus_special_rate
  }
  return 0
}

// 获取显示用的状态文本
const getStatusTextForDisplay = (item: any) => {
  // 见单奖、直推奖、分红：都显示为已到账
  if (item.income_type === 1 || item.income_type === 3 || item.income_type === 4) {
    return '已到账'
  }
  // 平级奖：根据特殊解冻标记和冻结状态显示
  if (item.income_type === 2) {
    // 如果有特殊解冻标记，直接显示已到账
    if (hasSpecialUnfreeze.value) {
      return '已到账'
    }
    const frozenAmount = getLevelBonusFrozenAmount(item)
    if (frozenAmount > 0) {
      return '部分冻结'
    }
    return '已到账'
  }
  return getStatusText(item.status)
}

// 获取状态样式类
const getStatusClass = (status: number) => {
  switch (status) {
    case 1:
      return 'success'
    case 2:
      return 'frozen'
    case 3:
      return 'invalid'
    default:
      return 'pending'
  }
}

// 格式化时间
const formatTime = (timestamp: number) => {
  if (!timestamp) return ''
  const date = new Date(timestamp * 1000)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  // 小于1小时显示分钟
  if (diff < 3600000) {
    return Math.floor(diff / 60000) + '分钟前'
  }
  // 小于24小时显示小时
  if (diff < 86400000) {
    return Math.floor(diff / 3600000) + '小时前'
  }
  // 大于24小时显示日期
  return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 计算解冻剩余时间（秒）
const getUnfreezeTimeLeft = (item: any) => {
  // 如果有特殊解冻标记，不显示倒计时
  if (hasSpecialUnfreeze.value) {
    return 0
  }
  
  if (!item.frozen_amount || parseFloat(item.frozen_amount) <= 0) {
    return 0
  }
  
  // 使用后端返回的count_down字段（毫秒转秒）
  if (item.count_down && item.count_down > 0) {
    return Math.floor(item.count_down / 1000)
  }
  
  return 0
}

// 获取解冻文本
const getUnfreezeText = (item: any) => {
  if (item.income_type === 2) {
    return '后解冻20%'
  } else {
    return '后自动解冻'
  }
}

// 解冻倒计时结束
const onUnfreezeTimeEnd = async (incomeId: number) => {
  console.log('解冻倒计时结束，收益ID:', incomeId)
  
  try {
    // 调用后端接口触发自动解冻
    const res = await manualUnfreezeIncome({ 
      income_id: incomeId,
      is_auto: 1 // 标识为自动解冻
    })
    
    if (res.code === 1) {
      uni.showToast({
        title: '收益已自动解冻',
        icon: 'success'
      })
    } else {
      console.log('自动解冻失败:', res.msg)
    }
  } catch (error) {
    console.error('自动解冻接口调用失败:', error)
  } finally {
    // 刷新数据
    refreshData()
  }
}


</script>

<style lang="scss" scoped>
@import './income.scss';
</style>
